package promote.brozen.utils.media.images.webp;

import com.luciad.imageio.webp.WebPReadParam;
import com.luciad.imageio.webp.WebPWriteParam;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.FileImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

/**
 * @author Brozen
 * @date 2020/1/7 10:04 AM
 */
public class WebpUtils {

    public static void encode(File inputFile, File outputFile) throws IOException {
        BufferedImage image = ImageIO.read(inputFile);

        ImageWriter writer = ImageIO.getImageWritersByMIMEType("image/webp").next();

        WebPWriteParam writeParam = new WebPWriteParam(writer.getLocale());
        writeParam.setCompressionMode(WebPWriteParam.MODE_DEFAULT);

        writer.setOutput(new FileImageOutputStream(outputFile));
        writer.write(null, new IIOImage(image, null, null), writeParam);

    }

    public static void decode(File inputFile, File outputFile) throws IOException {
        ImageReader reader = ImageIO.getImageReadersByMIMEType("image/webp").next();

        WebPReadParam readParam = new WebPReadParam();
        readParam.setBypassFiltering(true);

        reader.setInput(new FileImageInputStream(inputFile));

        BufferedImage image = reader.read(0, readParam);

        ImageIO.write(image, "jpg", outputFile);
    }




    public static void main(String[] args) throws IOException {
        File in = new File("/Users/mac/Downloads/新版漫威弹簧公仔详情页12款_01.jpg");
        File out = new File("/Users/mac/Downloads/test.webp");

        long s = System.currentTimeMillis();
//        WebpUtils.encode(in, out);
        long e = System.currentTimeMillis();
        System.out.println("ms" + (e - s));

        WebpUtils.decode(out, new File("/Users/mac/Downloads/out.jpg"));
    }
}
